﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp2
{
    public partial class Editform : Form
    {
        public Editform()
        {
            InitializeComponent();
        }

        
        private int id;

        public Editform(int Id, string Title, string Author, string TGreatedTime)
        {
            InitializeComponent();
            this.id  = Id;
            txtTitle.Text = Title  ;
            txtAuthor.Text = Author ;
            txtCreatedTime.Text = TGreatedTime;
            txtID.Text = Id.ToString();
           

        }

        private void button1_Click(object sender, EventArgs e)//确定保存键
        {


            var Id = txtID.Text;
            var Title = txtTitle.Text;
            var Author = txtAuthor.Text;
            var CreatedTime = txtCreatedTime.Text ;
            var ava = !string.IsNullOrEmpty(Title );
            //更新
            if (id  > 0)
            {
                if (ava )
                {   
                    var sql = string.Format("update Articles set Title ='{0}',Author='{1}',CreatedTime = '{2}' where id={3}", Title ,Author  , CreatedTime, id  );
                    var res = DbHelper.AddOrEdiOrDeleteSava(sql);
                    if (res == 1)
                    {
                        MessageBox.Show("更新成功！", "提示");
                        this.DialogResult = DialogResult.Yes;
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("更新失败", "提示");
                        this.Close();
                    }

                }
            }
            else//新增
            {
                if (ava )
                {
                    
                    var sql = string.Format("set identity_insert Articles ON  insert into Articles (Id,Title,Author,CreatedTime)values({0},'{1}','{2}','{3}')", Id,Title  , Author, CreatedTime);
                    var res = DbHelper.AddOrEdiOrDeleteSava(sql);
                    if (res == 1)
                    {
                        MessageBox.Show("添加成功！", "提示");
                        this.DialogResult = DialogResult.Yes;
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("添加失败", "提示");
                        this.Close();
                    }

                }

            }

        }

        private void button2_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.No;
            this.Close();
        }
    }
}
